//
//  BRCouponsCenterVC.m
//  Kexu
//
//  Created by IOS on 2023/7/25.
//

#import "BRCouponsCenterVC.h"
#import "BRCouponsBaseCell.h"
#import "YGCategoryView.h"
#import "BRCouponsPopupView.h"

@interface BRCouponsCenterVC ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    NSInteger _offset;
    NSMutableArray *_dataList;
}

@property (nonatomic,assign) NSInteger requestType;

@property (nonatomic,strong) YGCategoryCustomView *couponTypeView;

@property (nonatomic,strong) UIView *sectionView;

@property (nonatomic,strong) BRRedeemPopupView *redeemView;

@property (nonatomic,assign) NSInteger selIndex;
@property (nonatomic,assign) NSInteger redeemIndex;

@end

@implementation BRCouponsCenterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    _dataList = [NSMutableArray array];
    [self setUI];
    
    [self addRefreshActionForView:self.tableView];
    [self addLoadMoreActionForView:self.tableView];
    
    self.tableView.mj_footer.hidden = YES;
    
    [self reqestPoint];
    
    [self br_blockAction];
}

- (void)handleListRefreshAction {
    _offset = 0;
    [self reqestPoint];
}

- (void)handleListLoadMoreAction {
    _offset += 20;
    [self requeCouponList];
}

#pragma mark - request --
- (void)reqestPoint {
    
    WS(weakSelf);
    [BRUserManager requestPoints:^{
//        weakSelf.pointsView.pointStr = [NSString stringWithFormat:@"%ld",[BRUserManager share].point];
        
        [weakSelf requeCouponList];
    } faile:^{
        
    }];
}


- (void)requeCouponList {
    
    NSDictionary *dic;
    dic = @{@"offset":@(_offset),@"applyType":@(self.selIndex)};
    NSString *url = [BRAPI couponsList];

    [self.tableView ly_startLoading];
    [[BRRequestManager shared] GET:url params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSLog(@"%@",dataDict);
        if (self->_offset == 0) {
            [self->_dataList removeAllObjects];
        }
        NSInteger allC = self->_dataList.count;
        NSArray *list = [BRCouponListModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"]];
        [self->_dataList addObjectsFromArray:list];
        if (self->_dataList.count < allC + kPageSize || self->_dataList.count == 0 ) {
            self.tableView.mj_footer.hidden = YES;
        }
        
        [self.tableView reloadData];
        [self showBREmptyView:self.tableView];
        [self handleEndRefreshForView:self.tableView];
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self showBRErrorView:self.tableView];
        [self handleEndRefreshForView:self.tableView];
    }];
}
// 兑换
- (void)requestRedemm:(BRCouponModel *)dto {
    
    // 点击兑换
    [BRHud showInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[BRAPI redeemCoupons],self.redeemView.listDto.couponId];
    [[BRRequestManager shared] POST:url params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSLog(@"积分兑换成功 - %@",dataDict);
        [self reqestPoint];
        [BRHud hiddenInView:self.view];
        [BRHud showAutoSuccInView:self.view];
        [self.redeemView hidd];
        if (self.redeemSuccBlock) self.redeemSuccBlock();
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
    
    
}


#pragma mark - func --

- (void)br_blockAction {
    WS(weakSelf);
    self.redeemView.redeemBlock = ^(id model) {
        [weakSelf requestRedemm:(BRCouponModel *)model];
    };
    
    self.couponTypeView.itemSeletedBlock = ^(NSInteger index) {
        weakSelf.selIndex = index;
    };
}

- (void)setSelIndex:(NSInteger)selIndex {
    _selIndex = selIndex;
    _offset = 0;
    [self requeCouponList];
}

- (void)br_showRedeem:(NSInteger)index title:(NSString *)title{
    
    self.redeemIndex = index;
    // 点击兑换
    BRCouponListModel *dto = _dataList[index];
    self.redeemView.listDto = dto;
    self.redeemView.titleL.text = title;
    [self.redeemView show];
}


#pragma mark - tableView Delegate --

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return _dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRCouponListModel *dto = _dataList[indexPath.row];
    
    NSString *identifier = [NSString stringWithFormat:@"BRCouponCenterCell_%ld_%ld",self.selIndex,dto.couponId];
    
    BRCouponCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[BRCouponCenterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.listDto = dto;
    
    WS(weakSelf);
    cell.openBlock = ^(BOOL open) {
        if (open) [tableView beginUpdates];
        if (!open) [tableView endUpdates];
        
    };
    BRWeakObj(cell);
    cell.progressView.redeemBlock = ^{
        [weakSelf br_showRedeem:indexPath.row title:cellWeak.typeL.text];
    };
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    
}


#pragma mark - scroller --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
 
    
//    NSLog(@"%.2f",_headView.mj_h);
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat newoffsetY = offsetY;
    CGFloat maxY = 0;
    // 临界值150，向上拖动时变透明
    
    [self br_changSupperView:newoffsetY <= maxY];
}

- (void)br_changSupperView:(BOOL)defaultV {
    
    self.sectionView.hidden = defaultV;
}

#pragma mark - UI --
- (void)setUI {
    
    BRNavView *navV = [self br_createTop:Localized(@"coupon_couponCenter")];
    
    self.tableView.estimatedRowHeight = 134;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    [self.tableView registerClass:[BRCouponCenterCell class] forCellReuseIdentifier:@"BRCouponCenterCell"];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.frame = CGRectMake(0, kSafeAreaTopHeight + 58, kScreenWidth, kScreenHeight - (kSafeAreaTopHeight + 58));
    
    self.sectionView = [[UIView alloc] init];
    self.sectionView.hidden = YES;
    self.sectionView.backgroundColor = UIColor.whiteColor;
    [self.sectionView br_addBaseShadowDown];
    [self.view addSubview:self.sectionView];
    [self.sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(72 + kSafeAreaTopHeight);
        make.top.offset(0);
        make.left.right.offset(0);
    }];
    
    UIView *bfoot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 14)];
    self.tableView.tableFooterView = bfoot;
    
    [self.view addSubview:self.couponTypeView];
    [self.couponTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.offset(kSafeAreaTopHeight + 14);
        make.height.mas_equalTo(44);
    }];
    
    [self.view addSubview:self.redeemView];
    
    [self.view bringSubviewToFront:navV];
}

- (YGCategoryCustomView *)couponTypeView {
    if (_couponTypeView == nil) {
        _couponTypeView = [[YGCategoryCustomView alloc] initWithFrame:CGRectMake(14, 14, kScreenWidth - 28, 44) titles:@[Localized(@"coupon_generalCoupon"),Localized(@"coupon_merchantCoupon"),]];
      
    }
    return _couponTypeView;
}

- (BRRedeemPopupView *)redeemView {
    if (_redeemView == nil) {
        _redeemView = [[BRRedeemPopupView alloc] init];
        _redeemView.frame = self.view.bounds;
    }
    
    return _redeemView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
